#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>

extern errno;

char usage[] = "Usage : ./client.out [ip] [port]";
std::string ip = "119.29.155.99";
uint16_t port = 12312;

int main(int argc, char *argv[])
{
    if(argc > 3 || argc == 2)
    {
        std::cout << usage << std::endl;
        return 3;
    }
    if(argc == 3)
    {
        std::string ip = argv[1];
        uint16_t port = std::stoi(argv[2]);
    }

    //客户端无需显示bind
    //connect建立连接
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr(ip.c_str());

    bool reconnet = false;
    int cnt = 5;
    while (true)
    {
        // 3. 开始通信
        std::string str;
        std::cout << "please Enter@";
        std::cin >> str;
        if (str == "quit")
        {
            break;
        }

        reconnet = true;
        cnt = 5;
        // 1. 建立socket
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            perror("socket error:");
            close(sockfd);
            return 2;
        }

        do
        {
            int ret = connect(sockfd, (struct sockaddr *)&addr, sizeof(addr));
            if (ret < 0)
            {
                reconnet = true;
                printf("reset conncet: %d\n", cnt--);
                sleep(2);
            }
            else
            {
                reconnet = false; // 连接成功
            }
        } while (reconnet && cnt);

        if (cnt == 0)
        {
            close(sockfd);
            break;
        }

        int n = write(sockfd, str.c_str(), str.size());
        if (n < 0)
        {
            printf("读错误: %s", strerror(errno));
            close(sockfd);
            continue;
        }

        char buff[1024];
        n = read(sockfd, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n] = '\0';
            std::cout << buff << std::endl;
        }
        else if (n < 0)
        {
            printf("读错误: %s", strerror(errno));
            close(sockfd);
            continue;
        }
        else if (n == 0)
        {
            printf("服务器断开,准备重连\n");
            reconnet = true;
            cnt = 5;
        }
        close(sockfd);
    }
    return 0;
}